package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.login.LoginDAOImpl;
import tt.dz.biz.dao.thirdaccount.ThirdAccountDaoImpl;
import tt.dz.biz.dao.user.OperRoleDAO;
import tt.dz.biz.dao.user.UserDAOImpl;
import tt.dz.biz.dao.verifycode.MsVerifyCodeDAOImp;
import tt.dz.common.BusinessException;
import tt.dz.common.DateUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.Common;
import tt.dz.common.DzDigester;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.ExceptionErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.MsLoginHisVO;
import tt.dz.vo.OperListVO;
import tt.dz.vo.OperRoleVO;
import tt.dz.vo.UserBaseVO;
import tt.dz.vo.UserDetailVO;
import tt.dz.vo.VerifyCodeVO;

@Service("rpcLoginService")
public class RPCLoginService
  implements RPCBaseService
{
  @Resource(name="loginDAO")
  private LoginDAOImpl loginDao;
  @Resource(name="userDAO")
  private UserDAOImpl userDao;
  @Resource(name="msVerifyCodeDAO")
  private MsVerifyCodeDAOImp msVerifyCodeDAO;
  @Resource(name="operRoleDAO")
  private OperRoleDAO operRoleDAO;
  @Resource(name="thirdAccountDao")
  private ThirdAccountDaoImpl thirdAccountDao;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
  {
    JSONObject resultJson = new JSONObject();
    MsLoginHisVO tmpLogVO = new MsLoginHisVO();
    tmpLogVO.setIsSuccess(Integer.valueOf(0));
    try
    {
      Object req = ((GenericRecord)request).get("loginReq");
      String tradeReq = req.toString();
      
      JSONObject jsonObj = JSON.parseObject(tradeReq);
      
      String tmpMobileNo = jsonObj.getString("mobileNo");
      String tmpUserId = jsonObj.getString("userId");
      String tmpPassword = jsonObj.getString("password");
      Integer tmpLoginType = jsonObj.getInteger("loginType");
      

      String tmpMerchantCode = jsonObj.getString("merchantCode");
      
      tmpLogVO.setLongitude(jsonObj.getDouble("longitude"));
      tmpLogVO.setLatitude(jsonObj.getDouble("latitude"));
      tmpLogVO.setTerminalType(jsonObj.getString("terminalType"));
      
      resultJson.put("isSuccess", Integer.valueOf(0));
      if (((StringUtils.isBlank(tmpMobileNo)) && (StringUtils.isBlank(tmpUserId))) || 
        ((StringUtils.isNotBlank(tmpMobileNo)) && (
        (StringUtils.isBlank(tmpPassword)) || (StringUtils.isBlank(tmpMerchantCode)))) || (
        (StringUtils.isNotBlank(tmpUserId)) && (StringUtils.isBlank(tmpPassword))))
      {
        resultJson.put("errorMsg", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.getDesc());
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
      }
      boolean isSMSCompare = true;
      if (tmpLoginType.intValue() == 0)
      {
        isSMSCompare = false;
        if (StringUtils.isBlank(tmpPassword)) {
          resultJson.put("hasPwd", DzConstants.Common.ZREO);
        } else {
          resultJson.put("hasPwd", DzConstants.Common.ONE);
        }
        VerifyCodeVO verifyCodeVO = this.msVerifyCodeDAO.getVerifyCodeByPhone(tmpMobileNo);
        if (verifyCodeVO != null)
        {
          String content = verifyCodeVO.getContent();
          if (StringUtils.isNotBlank(content)) {
            if (StringUtils.equals(tmpPassword, content))
            {
              isSMSCompare = true;
            }
            else
            {
              resultJson.put("errorMsg", DzErrorCode.UserErrorCode.BAD_SMS_CODE.getDesc());
              resultJson.put("errorCode", DzErrorCode.UserErrorCode.BAD_SMS_CODE.value());
            }
          }
        }
        else
        {
          resultJson.put("errorMsg", DzErrorCode.UserErrorCode.NOT_SEND_SMS_CODE.getDesc());
          resultJson.put("errorCode", DzErrorCode.UserErrorCode.NOT_SEND_SMS_CODE.value());
        }
      }
      if (isSMSCompare)
      {
        UserBaseVO tmpUser;
//        UserBaseVO tmpUser;
        if (tmpLoginType.intValue() == 3)
        {
          tmpUser = this.thirdAccountDao.queryByBindTypeAndThirdUuuid(tmpMobileNo, tmpMerchantCode);
        }
        else
        {
//          UserBaseVO tmpUser;
          if (StringUtils.isNotBlank(tmpMobileNo)) {
            tmpUser = this.userDao.getUserBaseByUserId(null, tmpMobileNo, tmpMerchantCode);
          } else {
            tmpUser = this.userDao.getUserById(tmpUserId);
          }
        }
        if (null == tmpUser)
        {
          resultJson.put("errorMsg", DzErrorCode.UserErrorCode.USER_NOT_FOUND.getDesc());
          resultJson.put("errorCode", DzErrorCode.UserErrorCode.USER_NOT_FOUND.value());
        }
        else if (tmpUser.getIsLocked().intValue() == 1)
        {
          tmpLogVO.setUserId(tmpUser.getUserId());
          resultJson.put("errorMsg", DzErrorCode.UserErrorCode.USER_LOCKED.getDesc());
          resultJson.put("errorCode", DzErrorCode.UserErrorCode.USER_LOCKED.value());
          log(tmpLogVO);
        }
        else
        {
          tmpLogVO.setUserId(tmpUser.getUserId());
          if (tmpLoginType.intValue() == 1)
          {
            if (StringUtils.isBlank(tmpUser.getPassword()))
            {
              resultJson.put("errorMsg", DzErrorCode.UserErrorCode.NO_PASSWORD_SETTED.getDesc());
              resultJson.put("errorCode", DzErrorCode.UserErrorCode.NO_PASSWORD_SETTED.value());
              resultJson.put("hasPwd", DzConstants.Common.ZREO);
              return resultJson.toJSONString();
            }
            resultJson.put("hasPwd", DzConstants.Common.ONE);
            if (StringUtils.equals(DzDigester.md5ForUser(tmpPassword, tmpUser.getSalt()), tmpUser
              .getPassword()))
            {
              resultJson.put("isSuccess", Integer.valueOf(1));
              tmpLogVO.setIsSuccess(Integer.valueOf(1));
              log(tmpLogVO);
            }
            else
            {
              resultJson.put("errorMsg", DzErrorCode.UserErrorCode.BAD_PWD.getDesc());
              resultJson.put("errorCode", DzErrorCode.UserErrorCode.BAD_PWD.value());
            }
          }
          else if ((tmpLoginType.intValue() == 0) && (isSMSCompare))
          {
            resultJson.put("isSuccess", Integer.valueOf(1));
            tmpLogVO.setIsSuccess(Integer.valueOf(1));
            log(tmpLogVO);
          }
          else if (tmpLoginType.intValue() == 3)
          {
            resultJson.put("isSuccess", Integer.valueOf(1));
            resultJson.put("hasPwd", DzConstants.Common.ZREO);
            resultJson.put("errorMsg", "");
            resultJson.put("errorCode", "");
            tmpLogVO.setIsSuccess(Integer.valueOf(1));
            log(tmpLogVO);
          }
          else if (tmpLoginType.intValue() != 2) {}
          if (resultJson.getInteger("isSuccess").intValue() == 1)
          {
            if (tmpUser.getUserType().intValue() == 1)
            {
              OperListVO oper = new OperListVO();
              oper.setManagerId(tmpUser.getUserId());
              
              List<OperRoleVO> roleList = this.operRoleDAO.queryOperRoleByOper(oper);
              resultJson.put("roleList", roleList);
            }
            UserDetailVO detail = this.userDao.getUserDetailByUserId(tmpUser.getUserId());
            resultJson.put("userName", tmpUser.getName());
            resultJson.put("nickName", detail.getNickName());
            resultJson.put("userId", tmpUser.getUserId());
            resultJson.put("userType", tmpUser.getUserType());
            resultJson.put("notifyUrl", tmpUser.getNotifyUrl());
            resultJson.put("isLocked", tmpUser.getIsLocked());
            resultJson.put("headUrl", detail.getHeadUrl());
            
            resultJson.put("adddetail", detail.getAddDetail());
            resultJson.put("eleType", detail.getEletype());
          }
        }
      }
    }
    catch (BusinessException e)
    {
      resultJson.put("errorMsg", e.getStatusDescribe());
      resultJson.put("errorCode", e.getStatusCode());
    }
    catch (Exception e)
    {
      resultJson.put("errorMsg", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.getDesc());
      resultJson.put("errorCode", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value());
      LogUtil.error("登录异常，参数request为：" + request, e);
    }
    log(tmpLogVO);
    
    return resultJson.toJSONString();
  }
  
  private void log(MsLoginHisVO aObj)
  {
    try
    {
      aObj.setLoginTime(DateUtil.getDBCurrentTime());
      this.loginDao.log(aObj);
    }
    catch (Exception e)
    {
      LogUtil.error("日志记录异常", e);
    }
  }
}
